package com.yun.zhong.fu.codelianxi.service;

import com.yun.zhong.fu.codelianxi.entity.PageInfo;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.sql.Date;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

/**
 * @Author RenPu
 * @Date 2021/1/18 14:22
 * @Version 1.0
 * @Description: 批量文件上传的业务层
 **/
@Service
public class ImagesService {

    public String addMessage(List<MultipartFile> listfile, HttpServletRequest request) {

        final String[] imgUrl = {""};


        listfile.forEach(file -> {
            try {
                // 图片路径
                String resultPath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath() + "/static/img/upload/";
                //String userLogoPath = resultPath + messages.getUserId() + "/";
                //ResultMap.PROJECT_DIRECTORY+
                String uploadImgPath = request.getSession().getServletContext().getRealPath("static/img/upload") + "/";

                //上传
                String filename = upload(file, uploadImgPath, file.getOriginalFilename());
                if (filename != null) {
                    imgUrl[0] += new File(uploadImgPath).getName() + "/" + filename + ",";
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        });

        return imgUrl[0];
    }


    public String upload(MultipartFile file, String path, String fileName) throws Exception {
        // 生成新的文件名
        String realPath = path + "/" + UUID.randomUUID().toString().replace("-", "") + fileName.substring(fileName.lastIndexOf("."));

        File dest = new File(realPath);
        // 判断文件父目录是否存在
        if (!dest.getParentFile().exists()) {
            dest.getParentFile().mkdir();
        }
        // 保存文件
        file.transferTo(dest);
        return dest.getName();
    }


}
